package yf.mall.utils;


import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * description: 属性复制的bean
 *
 * @author Careerly
 * @version V1.0
 * @date 2020/2/4 2:30 PM
 */
public class CachedBeanCopier {

    private static final Map<String, BeanCopier> BEAN_COPIERS = new ConcurrentHashMap<>();

    public static void copy(Object srcObj, Object destObj) {

        String key = genKey(srcObj.getClass(), destObj.getClass(), false);

        BeanCopier copier = null;

        if (!BEAN_COPIERS.containsKey(key)) {
            copier = BeanCopier.create(srcObj.getClass(), destObj.getClass(), false);
            BEAN_COPIERS.put(key, copier);
        } else {
            copier = BEAN_COPIERS.get(key);
        }
        copier.copy(srcObj, destObj, null);

    }


    /**
     * description: 带自定义转换器进行转换
     *
     * @param srcObj    源对象
     * @param destObj   目标对象
     * @param converter 目标转换器
     * @return
     * @author Careerly
     * @date 2020/2/4 4:30 PM
     **/
    public static void copy(Object srcObj, Object destObj, Converter converter) {

        String key = genKey(srcObj.getClass(), destObj.getClass(), true);

        BeanCopier copier = null;

        if (!BEAN_COPIERS.containsKey(key)) {
            copier = BeanCopier.create(srcObj.getClass(), destObj.getClass(), true);
            BEAN_COPIERS.put(key, copier);
        } else {
            copier = BEAN_COPIERS.get(key);
        }
        copier.copy(srcObj, destObj, converter);
    }

    private static String genKey(Class<?> srcClazz, Class<?> destClazz, boolean useConverter) {
        return srcClazz.getName() + destClazz.getName() + useConverter;
    }
}  